//
//  ChooseImageViewController.m
//  XDBaseFrameWork
//
//  Created by xindao on 14-9-25.
//  Copyright (c) 2014年 XD-XY. All rights reserved.
//

#import "ChooseImageViewController.h"
#import "PhotoDetailViewController.h"
#import "ChooseImageRootViewController.h"
//#import "XHImageViewer.h"


//支付宝客户端头文件
#import "DataSigner.h"
#import "AlixPayResult.h"
#import "DataVerifier.h"
#import "AlixPayOrder.h"
#import "PartnerConfig.h"
#import "AlixLibService.h"

@interface ChooseImageViewController ()

@end


@implementation ChooseImageViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    sel = @selector(paymentResult:);

    self.titleLabel.text = _titleStr;

    imageUrlArray = [[NSMutableArray alloc] init];

    dataArray = [[NSMutableArray alloc] init];

    myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, UI_SCREEN_WIDTH, UI_MAINSCREEN_HEIGHT-2*UI_NAVIGATION_BAR_HEIGHT) style:UITableViewStylePlain];
    myTableView.dataSource = self;
    myTableView.delegate = self;
    myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;

    if (_canChoose) {
        UIView * downView = [UIView initViewRect:CGRectMake(0, height_y(myTableView), UI_SCREEN_WIDTH, UI_NAVIGATION_BAR_HEIGHT) andBackGroudColor:RGBA(243, 243, 243, 1)];
        [self.contentView addSubview:downView];

        showLB = [UILabel initLabelText:@"当前已选0张" andRect:CGRectMake(20,12,150,20) andBackGroudColor:[UIColor clearColor] andTextFont:[UIFont systemFontOfSize:15] andTextColor:UIColorFromRGB(0x453d35) andTextAlignment:NSTextAlignmentLeft];
        [downView addSubview:showLB];

        UIButton * overBtn = [UIButton initButton:CGRectMake(UI_SCREEN_WIDTH-65, 7.5f, 55, 29) btnNorImage:[UIImage imageNamed:@"overBtn"] btnHighlightImage:[UIImage imageNamed:@"overBtn"] btnTitle:@"完成" titleColor:[UIColor whiteColor] titleFont:[UIFont systemFontOfSize:15]];
        [overBtn addTarget:self action:@selector(showAlertView) forControlEvents:UIControlEventTouchUpInside];
        [downView addSubview:overBtn];
        
        if ([_phototype isEqualToString:@"Base"]) {
            UIView * footer = [UIView initViewRect:CGRectMake(0, 0, UI_SCREEN_WIDTH, 88) andBackGroudColor:[UIColor clearColor]];
            
            UILabel * label1 = [UILabel initLabelText:[NSString stringWithFormat:@"共%@张",_allCount] andRect:CGRectMake(0, 5, UI_SCREEN_WIDTH, 20) andBackGroudColor:[UIColor clearColor] andTextFont:[UIFont systemFontOfSize:14] andTextColor:UIColorFromRGB(0x453d35) andTextAlignment:NSTextAlignmentCenter];
            [footer addSubview:label1];

            UILabel * label2 = [UILabel initLabelText:[NSString stringWithFormat:@"当前可选%@张底片，加%@元即可获得全部底片",_maxNumber,_photoPrice] andRect:CGRectMake(0, 25, UI_SCREEN_WIDTH, 20) andBackGroudColor:[UIColor clearColor] andTextFont:[UIFont systemFontOfSize:14] andTextColor:RGBA(238, 84, 80, 1) andTextAlignment:NSTextAlignmentCenter];
            [footer addSubview:label2];
            
            UIImage * image = [UIImage imageNamed:@"xiadan"];  //上左下右
            image = [image resizableImageWithCapInsets:UIEdgeInsetsMake(10,10,10,10)];
            UIButton * btn = [UIButton initButton:CGRectMake((UI_SCREEN_WIDTH-120)/2, 50, 120, 30) btnNorImage:image btnHighlightImage:image btnTitle:@"我要全部底片" titleColor:[UIColor whiteColor] titleFont:[UIFont systemFontOfSize:15]];
            [btn addTarget:self action:@selector(alertBuyMore) forControlEvents:UIControlEventTouchUpInside];
            [footer addSubview:btn];
            
            myTableView.tableFooterView = footer;
        }
    }else{
        myTableView.frame = CGRectMake(0, 0, UI_SCREEN_WIDTH, UI_MAINSCREEN_HEIGHT-UI_NAVIGATION_BAR_HEIGHT);
    }


    [self.contentView addSubview:myTableView];


    NSDictionary * dic;
    if ([_phototype isEqualToString:@"Base"]) {
        dic = @{@"OrderID":_orderID,
                @"Type":@"Base",
                @"OrderProdID":@"NO"};
    }else{
        if (_havePush) {
            dic = @{@"OrderID":_orderID,
                    @"Type":_phototype,
                    @"OrderProdID":_orderProID};
        }else{
            dic = @{@"OrderID":_orderID,
                    @"Type":@"Base",
                    @"OrderProdID":_orderProID};
        }
    }

    [self getDataWithDict:dic api:API_GETPHOTO];
    
}

- (void)alertBuyMore{
    UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"订单确认" message:[NSString stringWithFormat:@"购买全部底片：%@张\n应付金额：%@元",_allCount,_photoPrice] delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    alert.tag = 98765;
    [alert show];
}

-(void)getDataWithDict:(NSDictionary *)dict api:(NSString *)api
{

    if (![XDTools NetworkReachable]) {
        [XDTools showTips:brokenNetwork toView:self.contentView];
        return;
    }

    __weak ASIHTTPRequest *request = [XDTools postRequestWithDict:dict API:api];
    [request setCompletionBlock:^{
        [XDTools hideProgress:self.contentView];

        NSDictionary *tempDic = [XDTools  JSonFromString:[request responseString]];

        if([[tempDic objectForKey:@"status"]intValue] == 1){

            DDLOG(@"dic = %@",tempDic);

            if ([api isEqualToString:API_GETPHOTO]) {
                dataArray = [NSMutableArray arrayWithArray:tempDic[@"data"]];

                for (int i = 0; i < dataArray.count; i++) {
                    NSMutableDictionary * dict = [NSMutableDictionary dictionaryWithDictionary:dataArray[i]];
                    [dict setObject:@"NO" forKey:@"isSelect"];
                    [dataArray replaceObjectAtIndex:i withObject:dict];

                    [imageUrlArray addObject:dict[@"Photobig"]];
                }
                
                [myTableView reloadData];

            }else if ([api isEqualToString:API_PUSHPHOTO]) {

                [XDTools showTips:@"选择图片成功" toView:self.contentView];

                if ([_phototype isEqualToString:@"Base"]) {
                    [_delegate havePushIndex:0 photo:@"Base" photoCover:coverStr];
                }else{
                    [_delegate havePushIndex:_indexNum photo:_phototype photoCover:coverStr];
                }

                [self performSelector:@selector(backPrePage) withObject:nil afterDelay:1];

            }

        }else{
            [XDTools showTips:tempDic[@"msg"] toView:self.view];

        }

    }];

    [request setFailedBlock:^{
        [XDTools hideProgress:self.contentView];
    }];
    [request startAsynchronous];
    [XDTools showProgress:self.contentView];
}


#pragma mark - UITableView DataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [self getRowsWithArray:dataArray];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 104+4;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString * cellIde = @"imageCell";
    ChooseImageCell * cell = [tableView dequeueReusableCellWithIdentifier:cellIde];
    if (!cell) {
        cell = [[ChooseImageCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIde];
        cell.delegate = self;
        cell.canChoose = _canChoose;
    }

    [cell getDataWithArray:dataArray index:indexPath.row];
    return cell;
    
}

#pragma mark - UITableView Delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}



#pragma mark - ChooseImageCell Delegate
- (void)chooseImage:(UIButton *)sender{
    if (sum == [_maxNumber intValue]) {
        if (sender.selected) {
            [XDTools showTips:@"选片数量已达上限" toView:self.contentView];
            sender.selected = !sender.selected;
            return;
        }
    }
    if (sender.selected) {
        NSMutableDictionary * dic = [NSMutableDictionary dictionaryWithDictionary:dataArray[sender.tag - 10000]];
        [dic setObject:@"YES" forKey:@"isSelect"];
        [dataArray replaceObjectAtIndex:sender.tag-10000 withObject:dic];
        sum++;
    }else{
        NSMutableDictionary * dic = [NSMutableDictionary dictionaryWithDictionary:dataArray[sender.tag - 10000]];
        [dic setObject:@"NO" forKey:@"isSelect"];
        [dataArray replaceObjectAtIndex:sender.tag-10000 withObject:dic];
        sum--;
    }
    showLB.text = [NSString stringWithFormat:@"当前已选%d张",sum];
}

- (void)gotoDetail:(UIGestureRecognizer *)tap{
    PhotoDetailViewController *photoVC = [[PhotoDetailViewController alloc] init];
    photoVC.myArray = imageUrlArray;
    photoVC.dataArray = dataArray;
    photoVC.maxNumber = _maxNumber.intValue;
    photoVC.contentOffset = tap.view.tag-20000;
    photoVC.sum = sum;
    photoVC.canChoose = _canChoose;
    photoVC.delegate = self;
    [self.navigationController pushViewController:photoVC animated:YES];

}


#pragma mark - ImageDetail Delegate
- (void)choosePhotoDetail:(int)index isSelect:(BOOL)isSelect{
    
    NSMutableDictionary * dict = [NSMutableDictionary dictionaryWithDictionary:dataArray[index]];
    if (isSelect) {
        [dict setObject:@"YES" forKey:@"isSelect"];
        sum++;
    }else{
        [dict setObject:@"NO" forKey:@"isSelect"];
        sum--;
    }
    [dataArray replaceObjectAtIndex:index withObject:dict];
    [myTableView reloadData];


    showLB.text = [NSString stringWithFormat:@"当前已选%d张",sum];
}

- (void)showAlertView{
    if (sum < [_maxNumber intValue]) {
        [XDTools showTips:@"亲，再选几张吧" toView:self.contentView];
        return;
    }
    UIAlertView * alert = [[UIAlertView alloc] initWithTitle:nil message:@"亲，确认就选这些吗？提交之后不能更改哦" delegate:self cancelButtonTitle:@"再考虑一下" otherButtonTitles:@"我已经考虑好", nil];
    [alert show];
}


- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (alertView.tag == 98765) {
        if (buttonIndex) {
            [self buyAll];
        }
    }else{
        if (buttonIndex) {
            [self pushData];
        }
    }
    
}

- (void)buyAll{
    ChooseImageRootViewController * root = (ChooseImageRootViewController *)_delegate;
    root.needFresh = YES;
    //调支付，购买全部底片
    
    
    [XDTools sharedXDTools].chooseImageVC = self;
    
    [self payByKeHuDuan];
    
    
}

- (void)pushData{
    
    ChooseImageRootViewController * root = (ChooseImageRootViewController *)_delegate;
    root.needFresh = YES;

    NSMutableArray * picArray = [[NSMutableArray alloc] init];
    for (NSDictionary * dict in dataArray) {
        if ([dict[@"isSelect"] isEqualToString:@"YES"]) {
            [picArray addObject:dict[@"PhotoID"]];
            coverStr = dict[@"Photourl"];
        }
    }

    NSDictionary * dic = @{@"OrderProdID":_orderProID,
                           @"phototype":_phototype,
                           @"OrderID":_orderID,
                           @"PhotoID":[picArray JSONString]};
    [self getDataWithDict:dic api:API_PUSHPHOTO];
    
}

//#pragma mark - XHImageViewerDelegate
//
////- (UIView *)customBottomToolBarOfImageViewer:(XHImageViewer *)imageViewer {
////    return self.bottomToolBar;
////}
//
//- (void)imageViewer:(XHImageViewer *)imageViewer
//willDismissWithSelectedView:(UIImageView *)selectedView {
//    NSInteger index = [_imageViews indexOfObject:selectedView];
//    NSLog(@"willDismiss index : %d", index);
//}
//
//- (void)imageViewer:(XHImageViewer *)imageViewer
//didDismissWithSelectedView:(UIImageView *)selectedView {
//    NSInteger index = [_imageViews indexOfObject:selectedView];
//    NSLog(@"didDismiss index : %d", index);
//
//    for (ChooseImageCell * cell in [myTableView visibleCells]) {
//        [cell.firstIV insertSubview:cell.firstIV.selectBtn aboveSubview:selectedView];
//        [cell.secondIV insertSubview:cell.secondIV.selectBtn aboveSubview:selectedView];
//        [cell.thirdIV insertSubview:cell.thirdIV.selectBtn aboveSubview:selectedView];
//    }
//}
//
//- (void)imageViewer:(XHImageViewer *)imageViewer
//didChangeToImageView:(UIImageView *)selectedView {
//    NSInteger index = [_imageViews indexOfObject:selectedView];
//    NSLog(@"change to index : %d", index);
//}

#pragma mark - 判断行数
-(int)getRowsWithArray:(NSMutableArray *)clubArray
{
    int a = [clubArray count]/3;
    int b = [clubArray count]%3;
    int sum = 0;
    if(b>0){
        sum = a+1;
    }else{
        sum = a;
    }
    return sum;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



//通过客户端
-(void)payByKeHuDuan{
    
    //    AlixPay * alixpay = [AlixPay shared];
    //    int ret = [alixpay pay:orderString applicationScheme:appScheme];
    //
    //    if (ret == kSPErrorAlipayClientNotInstalled) {
    //        UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:@"提示"
    //                                                             message:@"您还没有安装支付宝快捷支付，请先安装。"
    //                                                            delegate:self
    //                                                   cancelButtonTitle:@"确定"
    //                                                   otherButtonTitles:nil];
    //        [alertView setTag:123];
    //        [alertView show];
    //    }
    
    BOOL yy =  [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"alipay://"]];
    
    if (!yy) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"支付提示" message:@"您还未安装客户端,建议网页支付" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        
        [alert show];
        
        return;
    }
    
    NSString *appScheme = @"com.xindao.meishimeike";
    NSString* orderInfo = [self getOrderInfo];
    NSString* signedStr = [self doRsa:orderInfo];
    
    NSString *orderString = [NSString stringWithFormat:@"%@&sign=\"%@\"&sign_type=\"%@\"",
                             orderInfo, signedStr, @"RSA"];
    NSLog(@"orderString:%@",orderString);
    
    [AlixLibService payOrder:orderString AndScheme:appScheme seletor:sel target:self];
    
}

//支付宝回调
-(void)paymentResultDelegate:(NSString *)result{
    
}

-(void)paymentResult:(NSString *)result{
    
}
-(NSString*)getOrderInfo
{
    
    //拼接商品信息
    AlixPayOrder *order = [[AlixPayOrder alloc] init];
    order.partner = PartnerID;
    order.seller = SellerID;
    

    
    
    order.productName = @"购买全部底片";
    order.tradeNO = _orderID;  //订单ID（由商家自行制定）   ///需要赋值
    order.productDescription = @"专业的摄影";;
    order.amount = _photoPrice; //商品价格
    
    //测试的
//    order.amount = @"0.01";
    
//    order.notifyURL = @"http://123.57.16.119/index.php?m=Api&c=Order&a=notify&code=alipay"; //回调URL
    order.notifyURL = @"http://www.meike365.cn/call_back.php";

    
	return [order description];
}

-(NSString*)doRsa:(NSString*)orderInfo
{
    id<DataSigner> signer;
    signer = CreateRSADataSigner(PartnerPrivKey);
    NSString *signedString = [signer signString:orderInfo];
    return signedString;
}



////支付成功后跳入
- (void)freshRootVC{
    ChooseImageRootViewController * root = (ChooseImageRootViewController *)_delegate;
    root.needFresh = YES;
    [self.navigationController popViewControllerAnimated:YES];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
